package com.qianfeng.day11.test;

import com.qianfeng.day11.util.Snowflake;
import redis.clients.jedis.Jedis;

public class MyThread1 extends Thread {
    @Override
    public void run() {
        for (int i = 0; i < 10; i++){
            Jedis jedis = RedisConnection.getJedis();

            // 抢先设置一个变量
            Long token = jedis.setnx("token", "1");

            // 如果抢失败，打印没有抢到优惠券
            if (token == 0){
                System.out.println("没有抢到优惠券");
            }
            // 如果抢到，那么开始买票，买完票，将变量删除，以提供别人抢的机会
            else{
                String num = jedis.get("num");
                int n = Integer.parseInt(num);
                if (n < 10){
                    try {
                        Thread.sleep(100);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    jedis.incr("num");
                    String name = String.valueOf(Snowflake.getInstance().nextId());
                    System.out.println("抢到一张优惠券, 订单号为：" + name);
                }
                jedis.del("token");
            }
        }
    }

    public static void main(String[] args) {
        for (int i = 0; i < 5; i++){
            MyThread1 thread = new MyThread1();
            thread.start();
        }
    }
}
